# 配置管理模块
# 负责从 YAML 配置文件读取和管理应用配置。

import os
import yaml
from typing import Dict, Any, Optional
from pathlib import Path

# 全局配置缓存
_config_cache: Optional[Dict[str, Any]] = None


def load_config(config_file: str = "config/config.yaml") -> Dict[str, Any]:
    # 加载配置文件
    # Args: config_file: 配置文件路径
    # Returns: Dict[str, Any]: 配置字典
    global _config_cache
    
    if _config_cache is not None:
        return _config_cache
    
    # 如果配置文件路径是相对路径，尝试从项目根目录查找
    config_path = Path(config_file)
    if not config_path.is_absolute() and not config_path.exists():
        # 尝试从当前脚本的父目录（项目根目录）查找
        current_file = Path(__file__).parent
        project_root = current_file.parent if current_file.name == "config" else current_file
        config_path = project_root / config_file
    
    if not config_path.exists():
        raise FileNotFoundError(f"配置文件不存在: {config_file} (尝试路径: {config_path})")
    
    try:
        with open(config_path, 'r', encoding='utf-8') as f:
            _config_cache = yaml.safe_load(f)
        
        print(f"配置文件加载成功: {config_file}")
        return _config_cache
        
    except yaml.YAMLError as e:
        raise ValueError(f"YAML 配置文件格式错误: {e}")
    except Exception as e:
        raise RuntimeError(f"加载配置文件失败: {e}")


def get_config(section: str = None, key: str = None, default: Any = None) -> Any:
    """获取配置值
    
    Args:
        section: 配置节名称
        key: 配置键名称
        default: 默认值
        
    Returns:
        Any: 配置值
    """
    if _config_cache is None:
        load_config()
    
    if section is None:
        return _config_cache
    
    if key is None:
        return _config_cache.get(section, default)
    
    return _config_cache.get(section, {}).get(key, default)


def reload_config(config_file: str = "config/config.yaml") -> Dict[str, Any]:
    """重新加载配置文件
    
    Args:
        config_file: 配置文件路径
        
    Returns:
        Dict[str, Any]: 配置字典
    """
    global _config_cache
    _config_cache = None
    return load_config(config_file)


def get_app_config() -> Dict[str, Any]:
    """获取应用配置"""
    return get_config("app", default={})


def get_logging_config() -> Dict[str, Any]:
    """获取日志配置"""
    return get_config("logging", default={})


def get_database_config() -> Dict[str, Any]:
    """获取数据库配置"""
    return get_config("database", default={})


def get_hospital_config() -> Dict[str, Any]:
    """获取医院配置"""
    return get_config("hospital", default={})


def get_batch_config() -> Dict[str, Any]:
    """获取分批处理配置"""
    hospital_config = get_hospital_config()
    saas_config = get_saas_config()
    
    return {
        "upload_batch_size": hospital_config.get("batch_size", 200),
        "timeout": saas_config.get("timeout", 30)
    }


def get_saas_config() -> Dict[str, Any]:
    """获取 SaaS 配置"""
    return get_config("saas", default={})


def get_scheduler_config() -> Dict[str, Any]:
    """获取定时任务配置"""
    return get_config("scheduler", default={})


def get_static_config() -> Dict[str, Any]:
    """获取静态文件配置"""
    return get_config("static", default={})


def get_development_config() -> Dict[str, Any]:
    """获取开发配置"""
    return get_config("development", default={})




def get_swagger_config() -> Dict[str, Any]:
    """获取 Swagger 配置"""
    return get_config("swagger", default={})


def get_testing_config() -> Dict[str, Any]:
    """获取测试配置"""
    return get_config("testing", default={})


# 便捷函数
def is_production_mode() -> bool:
    """检查是否为生产模式"""
    return get_config("logging", "production_mode", True)


def is_debug_data_enabled() -> bool:
    """检查是否启用详细数据输出"""
    return get_config("logging", "debug_data", False)


def is_mock_mode() -> bool:
    """检查是否为模拟模式"""
    return get_config("database", "mock_mode", True)

def get_shipping_config() -> Dict[str, Any]:
    """获取收货信息配置"""
    config = get_app_config()
    return config.get("shipping", {})

__all__ = [
    "load_config", "get_config", "reload_config",
    "get_app_config", "get_logging_config", "get_database_config",
    "get_hospital_config", "get_saas_config", "get_scheduler_config",
    "get_static_config", "get_development_config",
    "get_swagger_config", "get_testing_config", "get_batch_config",
    "is_production_mode", "is_debug_data_enabled", "is_mock_mode"
]
